package com.quanquan.store.controller.pagePoint;

import com.quanquan.store.controller.pagePoint.entity.Page;
import com.quanquan.store.controller.pagePoint.entity.PageData;
import com.quanquan.store.controller.pagePoint.entity.PageParams;
import com.quanquan.store.controller.pagePoint.request.PageDataRequest;
import com.quanquan.store.controller.pagePoint.service.PagePointService;
import enums.ResCodeEnum;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import utils.StringUtil;
import web.response.ResultBody;

import java.util.Date;
import java.util.List;

/**
 * @ClassName PagePointController
 * @Description
 * @Author Owen
 * @Date 2019/11/14 0014 下午 3:35
 * @Version V1.0
 **/
@RestController
@RequestMapping("/pagePoint")
public class PagePointController {

    @Autowired
    private PagePointService pagePointService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 添加页面埋点数据
     * @param pageDataRequest
     * @return
     */
    @PostMapping("/addPageData")
    public ResultBody addPageData(@RequestBody PageDataRequest pageDataRequest) {
        Page page = pagePointService.getPage(pageDataRequest.getPageUrl());
        if(null == page){
            page = new Page();
            page.setName("temp"+new Date().getTime());
            page.setPageUrl(pageDataRequest.getPageUrl());
            page.setCreateTime(new Date());
            page.setStatus(1);
            page = pagePointService.savePage(page);
        }

        PageData pageData = new PageData();
        pageData.setOpenid(pageDataRequest.getOpenid() == null ? "" : pageDataRequest.getOpenid());
        pageData.setPageId(page.getId());
        pageData.setCreateTime(new Date());
        pageData = pagePointService.savePageData(pageData);

        if(null != pageDataRequest.getPageParams()){
            List<PageParams> list = pageDataRequest.getPageParams();
            for (PageParams pageParams : list) {
                pageParams.setPageDataId(pageData.getId());
                pagePointService.savePageParams(pageParams);
            }
        }

        if(StringUtil.isNotEmpty(pageDataRequest.getOpenid())){
            amqpTemplate.convertAndSend("userExchange","updateTime",pageDataRequest.getOpenid());
        }

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "SUCCESS");
    }
}
